//专门用来存放关于收藏的所有接口
const Router = require('koa-router')
const login = new Router()
//! 拿到前端传过来的数据  koa-bodyparser
const bodyparser = require('koa-bodyparser')
const db = require('../utils/db')

//! 调用下面这个中间件，就可以拿到前端post过来的数据
login.use(bodyparser())

const APP_ID = "wxf42710c889e05a0b"  //开发者的appid
const APP_SECRET = "c3abd4e70bf22b136fbc1d3af602ea36"   //开发者的appsecret
const APP_URL = 'https://api.weixin.qq.com/sns/jscode2session'
var request = require("request");

login.post('/', async (ctx,next) => {
    console.log(ctx.request.body.code);
    var js_code = ctx.request.body.code
    console.log(APP_URL);
    var url = `${APP_URL}?appid=${APP_ID}&secret=${APP_SECRET}&js_code=${js_code}&grant_type=authorization_code`
    if (js_code) {
        let res = await new Promise((resolve, reject) => {
            return request(url, (error, response, body) => {
                // 这里要注意一下，body为string字符串，虽然我们得到的是这样一个东西：{"session_key":"xxx","openid":"xxx"}，但是它不是对象，所以我们需要把它转为对象
                resolve(JSON.parse(body))
            })
        })
        ctx.body = res
    } else {
        console.log('code 不存在')
    }
})

login.post('/openid', async ctx => {

    console.log(ctx.request.body.openid);
    if ( ctx.request.body.openid === "undefined" ) {
        ctx.body = '未获取用户openid'
    } else {
        console.log(ctx.request.body);
        //判断数据库中是否已经存有该openid
        var searchOpenidSql = `select * from user_class where openid="${ctx.request.body.openid}"`
        var result = await new Promise((resolve, reject) => {
            return db.query(searchOpenidSql, (err, data) => {
                if (err) throw err
                resolve(data)
            })
        })
        console.log(result);

        // //将访客信息插入visitor表
        // let timetd= Math.round(new Date() / 1000) //当前时间戳，精确到秒;首次注册时间
        // let insertVisitSql = `insert into visitYesday_class (openId,time) values('${ctx.request.body.openid}','${timetd}') `
        // let result0 = await new Promise((resolve, reject) => {
        //     return db.query(insertVisitSql, (err, data) => {
        //         if (err) throw err
        //          resolve(data)
        //      })
        //  })
        //  ctx.body = "插入访客数据成功"


        if (JSON.stringify(result) == "[]") {
            console.log(1);
            let timetd= Math.round(new Date() / 1000) //当前时间戳，精确到秒;首次注册时间
            //将用户信息插入user表
            let insertOpenidSql = `insert into user_class (openid,img,name,time) `
                    +`values('${ctx.request.body.openid}','${ctx.request.body.img}','${ctx.request.body.name}','${timetd}') ` 
            let insertResult = await new Promise((resolve, reject) => {
                return db.query(insertOpenidSql, (err, data) => {
                    if (err) throw err
                    resolve(data)
                })
            })
            ctx.body = '是个新用户，已记录到数据库中'
            console.log(ctx.body);
        } else {
            //二次请求&登录之后 更新用户头像和昵称
            if(ctx.request.body.img != ""){
            let updatemesSql = `update user_class set img="${ctx.request.body.img}",name="${ctx.request.body.name}" `
                        + `where openid='${ctx.request.body.openid}'`    
            let result = await new Promise ((reslove,reject)=>{
                return db.query(updatemesSql,(err,data)=>{
                    if(err) console.log(err);
                    reslove(data)
                })
            })
            }
            ctx.body = "修改成功,是老用户";

            let searchimgAndbodySql = `select img,name from user_class where openid = "${ctx.request.body.openid}"`
            let result = await new Promise ((reslove,reject)=>{
                return db.query(searchimgAndbodySql,(err,data)=>{
                    if(err) console.log(err);
                    reslove(data)
                })
            })
            ctx.body = result;
            console.log(ctx.body);
        }
        
    }
})
// //昨日(前24小时)注册量
// login.get('/loginnum', async ctx => {
//     let timetd= Math.round(new Date() / 1000) //当前时间戳，精确到秒
//     let timeytd = timetd-86400; //前24小时的时间戳
//     let data = await new Promise((reslove,reject) => {
//         return db.query(`select * from user_class where time > ${timeytd}`,(err,data) => {
//             if(err) console.log(err);
//             reslove(data);
//         })
//     })
//     ctx.body = data.length;
// })
// //昨日访客量
// login.get('/visitornum',async ctx => {
//     let timetd= Math.round(new Date() / 1000) //当前时间戳，精确到秒
//     let timeytd = timetd-86400; //前24小时的时间戳
//     let data = await new Promise((reslove,reject) => {
//         return db.query(`select * from visitYesday_class where time > ${timeytd}`,(err,data) => {
//             if(err) console.log(err);
//             reslove(data);
//         })
//     })
//     ctx.body = data.length;
// })


module.exports = login